﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Eksponent.CropUp.Config
{
    public static class JsonHelper
    {
        public static JavaScriptSerializer Serializer
        {
            get
            {
                var json = new JavaScriptSerializer();
                json.RegisterConverters(new[] { new NullableConverter<PointF>() });
                return json;
            }
        }

        public class NullableConverter<T> : JavaScriptConverter where T : struct
        {
            public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                if (dictionary == null) return null;

                return serializer.ConvertToType<T>(dictionary);
            }

            public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
            {

                var val = ((T?)obj);
                return val.HasValue ? (IDictionary<string, object>)serializer.DeserializeObject(serializer.Serialize(val.Value)) : null;
            }

            public override IEnumerable<Type> SupportedTypes
            {
                get { yield return typeof(T?); }
            }
        }
    }
}
